import { User } from "../model/User.js"
import { Op } from "sequelize";

async function queryALl(ctx) {
    let keyword = ctx.query.keyword
    let users;
    if (keyword) {
        users = await User.findAll({
            where: {
                [Op.or]: {
                    uname: {
                        [Op.like]: `%${keyword}%`
                    },
                    uage: {
                        [Op.like]: `%${keyword}%`
                    },
                }
            }
        })
    } else {
        users = await User.findAll()
    }
    ctx.body = {
        code: 200,
        msg: "请求成功",
        data: users
    }
}

async function queryById(ctx) {
    let id = ctx.params.id
    let user = await User.findByPk(id)
    ctx.body = {
        code: 200,
        msg: "请求成功",
        data: user
    }
}

async function delById(ctx) {
    let id = ctx.params.id
    await User.destroy({ where: { id } })
    ctx.body = {
        code: 200,
        msg: "请求成功",
        data: "删除成功"
    }
}

async function addUser(ctx) {
    let obj = ctx.request.body
    await User.create(obj)
    ctx.body = {
        code: 200,
        msg: "请求成功",
        data: "新增成功"
    }
}

async function editUser(ctx) {
    let id = ctx.params.id
    let obj = ctx.request.body
    await User.update(obj, { where: { id } })
    ctx.body = {
        code: 200,
        msg: "请求成功",
        data: "修改成功"
    }
}

export const users = [
    { method: "get", path: "/users", fn: queryALl },
    { method: "get", path: "/user/:id", fn: queryById },
    { method: "delete", path: "/user/:id", fn: delById },
    { method: "post", path: "/user", fn: addUser },
    { method: "put", path: "/user/:id", fn: editUser },
]